import 'package:craze/common/index.dart';
import 'package:craze/models/index.dart';
import 'package:craze/services/index.dart';
import 'package:craze/stores/index.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get_it/get_it.dart';
import 'package:go_router/go_router.dart';
import 'package:google_fonts/google_fonts.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:craze/stores/share_comment_store.dart';

class ShareDetailView extends StatefulWidget {
  final String shareId;
  const ShareDetailView({super.key, this.shareId = ''});

  @override
  State<ShareDetailView> createState() => _ShareDetailViewState();
}

class _ShareDetailViewState extends State<ShareDetailView> {
  SharePostModel? share;
  UserModel? user;
  List<UserModel> viewers = [];
  int currentPage = 0;
  late final PageController _pageController;

  final AuthStore _authStore = GetIt.I<AuthStore>();
  final UserService _userService = GetIt.I<UserService>();
  final ShareStore _shareStore = GetIt.I<ShareStore>();
  final CollectionService _collectionService = GetIt.I<CollectionService>();
  final ShareCommentStore _commentStore = ShareCommentStore(
    GetIt.I<AuthStore>(),
  );
  final TextEditingController _commentController = TextEditingController();
  final CollectionStore _collectionStore = GetIt.I<CollectionStore>();

  bool isFollowed = false;
  bool isCollected = false;

  @override
  void initState() {
    super.initState();
    _pageController = PageController();
    _loadData();
    _startAutoPlay();
    // 加载评论
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (widget.shareId.isNotEmpty) {
        _commentStore.loadComments(widget.shareId);
      }
    });
  }

  void _startAutoPlay() {
    Future.delayed(const Duration(seconds: 3), () {
      if (!mounted || share == null || share!.imageUrls.length <= 1) return;
      int nextPage = (currentPage + 1) % share!.imageUrls.length;
      _pageController.animateToPage(
        nextPage,
        duration: const Duration(milliseconds: 400),
        curve: Curves.easeInOut,
      );
      setState(() {
        currentPage = nextPage;
      });
      _startAutoPlay();
    });
  }

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  void _loadData() {
    final shareService = GetIt.I<ShareService>();
    share = shareService.getShareById(widget.shareId);
    if (share != null) {
      user = _userService.getUserById(share!.userId);
      viewers =
          share!.viewerIds
              .map((id) => _userService.getUserById(id))
              .whereType<UserModel>()
              .toList();
    }
    // 初始化关注和收藏状态
    if (user != null &&
        _authStore.isLoggedIn &&
        _authStore.currentUser != null) {
      isFollowed = _authStore.currentUser!.followingIds.contains(user!.id);
    }
    if (share != null &&
        _authStore.isLoggedIn &&
        _authStore.currentUser != null) {
      final shareInStore = _shareStore.shares.firstWhere(
        (s) => s.id == share!.id,
        orElse: () => share!,
      );
      isCollected = shareInStore.isCollected;
    }
    setState(() {});
  }

  Future<void> _toggleFollowUser() async {
    if (!_authStore.isLoggedIn ||
        _authStore.currentUser == null ||
        user == null) {
      LoginDialog.show(
        context,
        title: 'Login',
        description: 'Please login first',
      );
      return;
    }
    final currentUserId = _authStore.currentUser!.id;
    final targetUserId = user!.id;
    final wasFollowed = isFollowed;
    setState(() {
      isFollowed = !wasFollowed;
    });
    try {
      if (wasFollowed) {
        await _userService.unfollowUser(currentUserId, targetUserId);
      } else {
        await _userService.followUser(currentUserId, targetUserId);
      }
      _authStore.currentUser = _userService.getUserById(currentUserId);
    } catch (e) {
      setState(() {
        isFollowed = wasFollowed;
      });
      MyToast.showError(context, e.toString());
    }
  }

  Future<void> _toggleCollect() async {
    if (!_authStore.isLoggedIn || share == null) {
      LoginDialog.show(
        context,
        title: 'Login',
        description: 'Please login first',
      );
      return;
    }
    final wasCollected = isCollected;
    setState(() {
      isCollected = !wasCollected;
    });
    try {
      // 用 CollectionStore 统一收藏逻辑
      await _collectionStore.toggleShareCollection(share!.id);
      _loadData();
      await _collectionStore.loadUserCollections();
    } catch (e) {
      setState(() {
        isCollected = wasCollected;
      });
      MyToast.showError(context, e.toString());
    }
  }

  Future<void> _sendComment() async {
    if (!_authStore.isLoggedIn || _authStore.currentUser == null) {
      LoginDialog.show(
        context,
        title: 'Login',
        description: 'Please login first',
      );
      return;
    }
    final content = _commentController.text.trim();
    if (content.isEmpty || share == null) return;
    try {
      await _commentStore.addComment(share!.id, content);
      _commentController.clear();
      FocusScope.of(context).unfocus();
    } catch (e) {
      MyToast.showError(context, e.toString());
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(MyImages.commonBg),
            fit: BoxFit.cover,
          ),
        ),
        child: SafeArea(
          bottom: false,
          child:
              share == null
                  ? Center(child: CircularProgressIndicator())
                  : Stack(
                    children: [
                      // 主体内容整体可滚动
                      Positioned.fill(
                        child: Column(
                          children: [
                            // 顶部栏
                            Padding(
                              padding: EdgeInsets.symmetric(horizontal: 16.w),
                              child: Row(
                                children: [
                                  GestureDetector(
                                    onTap: () => GoRouter.of(context).pop(),
                                    child: Icon(
                                      MyIcons.iconBack,
                                      color: Colors.white,
                                      size: 22.sp,
                                    ),
                                  ),
                                  Expanded(
                                    child: Center(
                                      child: Text(
                                        'Share details',
                                        style: TextStyle(
                                          color: Colors.white,
                                          fontSize: 22.sp,
                                          fontFamily:
                                              GoogleFonts.mochiyPopOne()
                                                  .fontFamily,
                                          fontWeight: FontWeight.w400,
                                          height: 1.36,
                                        ),
                                      ),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: () {
                                      ReportDialog.show(
                                        context,
                                        title: 'Report',
                                        description:
                                            'Please select a reason for reporting this post.',
                                        onSubmit: (type) async {
                                          MyToast.showSuccess(
                                            context,
                                            'Report successful',
                                          );
                                          await getIt<ShareService>()
                                              .deleteSharePost(share!.id);
                                          await _shareStore.loadShares();
                                          GoRouter.of(context).pop();
                                        },
                                      );
                                    },
                                    child: Icon(
                                      MyIcons.iconReport,
                                      color: Colors.white,
                                      size: 28.sp,
                                    ),
                                  ),
                                ],
                              ),
                            ),
                            // 内容整体可滚动
                            Expanded(
                              child: SingleChildScrollView(
                                padding: EdgeInsets.only(
                                  bottom: 90.h,
                                ), // 留出底部输入框空间
                                child: Column(
                                  crossAxisAlignment: CrossAxisAlignment.start,
                                  children: [
                                    SizedBox(height: 16.h),
                                    // 大图轮播
                                    Container(
                                      margin: EdgeInsets.symmetric(
                                        horizontal: 20.w,
                                        vertical: 8.h,
                                      ),
                                      height: 256.h,
                                      width: double.infinity,
                                      child:
                                          share!.imageUrls.isEmpty
                                              ? Container(
                                                decoration: BoxDecoration(
                                                  borderRadius:
                                                      BorderRadius.circular(
                                                        16.r,
                                                      ),
                                                  color: Colors.grey[300],
                                                ),
                                              )
                                              : Stack(
                                                children: [
                                                  PageView.builder(
                                                    controller: _pageController,
                                                    itemCount:
                                                        share!.imageUrls.length,
                                                    onPageChanged:
                                                        (i) => setState(
                                                          () => currentPage = i,
                                                        ),
                                                    itemBuilder: (
                                                      context,
                                                      idx,
                                                    ) {
                                                      return ClipRRect(
                                                        borderRadius:
                                                            BorderRadius.circular(
                                                              16.r,
                                                            ),
                                                        child: Image.asset(
                                                          share!.imageUrls[idx],
                                                          fit: BoxFit.cover,
                                                          width:
                                                              double.infinity,
                                                          height: 200.h,
                                                        ),
                                                      );
                                                    },
                                                  ),
                                                  // 指示器
                                                  Positioned(
                                                    bottom: 10.h,
                                                    left: 0,
                                                    right: 0,
                                                    child: Row(
                                                      mainAxisAlignment:
                                                          MainAxisAlignment
                                                              .center,
                                                      children: List.generate(
                                                        share!.imageUrls.length,
                                                        (idx) => Container(
                                                          margin:
                                                              EdgeInsets.symmetric(
                                                                horizontal: 3.w,
                                                              ),
                                                          width: 8.w,
                                                          height: 8.w,
                                                          decoration: BoxDecoration(
                                                            color:
                                                                currentPage ==
                                                                        idx
                                                                    ? Colors
                                                                        .white
                                                                    : Colors
                                                                        .white54,
                                                            shape:
                                                                BoxShape.circle,
                                                          ),
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ],
                                              ),
                                    ),
                                    SizedBox(height: 18.h),
                                    // 用户信息、描述
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                      ),
                                      child: Column(
                                        crossAxisAlignment:
                                            CrossAxisAlignment.start,
                                        children: [
                                          // 用户信息行
                                          Row(
                                            children: [
                                              GestureDetector(
                                                onTap: () {
                                                  GoRouter.of(context).push(
                                                    AppRouter.otherProfile,
                                                    extra: {'userId': user?.id},
                                                  );
                                                },
                                                child: CircleAvatar(
                                                  radius: 22.r,
                                                  backgroundImage: AssetImage(
                                                    user?.avatar ??
                                                        'assets/images/touxiang1.png',
                                                  ),
                                                ),
                                              ),
                                              SizedBox(width: 8.w),
                                              Text(
                                                user?.name ?? '',
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 16.sp,
                                                  fontFamily:
                                                      GoogleFonts.mochiyPopOne()
                                                          .fontFamily,
                                                  fontWeight: FontWeight.w400,
                                                  height: 1,
                                                ),
                                              ),
                                              SizedBox(width: 8.w),
                                              GestureDetector(
                                                onTap: _toggleFollowUser,
                                                child: Container(
                                                  padding: EdgeInsets.symmetric(
                                                    horizontal: 8.w,
                                                    vertical: 4.h,
                                                  ),
                                                  decoration: BoxDecoration(
                                                    color:
                                                        isFollowed
                                                            ? Colors.grey
                                                            : Colors.blue,
                                                    borderRadius:
                                                        BorderRadius.circular(
                                                          12.r,
                                                        ),
                                                  ),
                                                  child: Text(
                                                    isFollowed
                                                        ? 'followed'
                                                        : '+follow',
                                                    style: TextStyle(
                                                      color: Colors.white,
                                                      fontSize: 13.sp,
                                                      fontWeight:
                                                          FontWeight.w600,
                                                    ),
                                                  ),
                                                ),
                                              ),
                                              Spacer(),
                                              // 收藏按钮
                                              GestureDetector(
                                                onTap: _toggleCollect,
                                                child: Container(
                                                  width: 37.w,
                                                  height: 37.w,
                                                  decoration: ShapeDecoration(
                                                    color: Colors.white
                                                        .withOpacity(0.06),
                                                    shape: OvalBorder(),
                                                  ),
                                                  child: Icon(
                                                    isCollected
                                                        ? MyIcons
                                                            .iconCollectFill
                                                        : MyIcons.iconCollect,
                                                    color:
                                                        isCollected
                                                            ? Colors.red
                                                            : Colors.white,
                                                    size: 20.sp,
                                                  ),
                                                ),
                                              ),
                                            ],
                                          ),
                                          SizedBox(height: 10.h),
                                          // 描述
                                          Text(
                                            share!.description,
                                            style: TextStyle(
                                              color: Colors.white,
                                              fontSize: 14.sp,
                                              height: 1.5,
                                            ),
                                          ),
                                          SizedBox(height: 10.h),
                                          // 已浏览头像
                                          Row(
                                            children: [
                                              ...List.generate(viewers.length, (
                                                idx,
                                              ) {
                                                return Transform.translate(
                                                  offset: Offset(
                                                    idx == 0 ? 0 : -10.w,
                                                    0,
                                                  ),
                                                  child: CircleAvatar(
                                                    radius: 14.r,
                                                    backgroundImage: AssetImage(
                                                      viewers[idx].avatar,
                                                    ),
                                                  ),
                                                );
                                              }),
                                              SizedBox(width: 6.w),
                                              Text(
                                                'Already viewed',
                                                style: TextStyle(
                                                  color: Colors.white,
                                                  fontSize: 11.sp,
                                                  fontFamily:
                                                      GoogleFonts.mochiyPopOne()
                                                          .fontFamily,
                                                  fontWeight: FontWeight.w400,
                                                  height: 1.45,
                                                ),
                                              ),
                                            ],
                                          ),
                                        ],
                                      ),
                                    ),
                                    SizedBox(height: 10.h),
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                      ),
                                      child: Divider(
                                        height: 1.h,
                                        color: Colors.white.withAlpha(150),
                                      ),
                                    ),
                                    SizedBox(height: 10.h),
                                    // 评论区
                                    Padding(
                                      padding: EdgeInsets.symmetric(
                                        horizontal: 16.w,
                                      ),
                                      child: Observer(
                                        builder:
                                            (_) => Column(
                                              crossAxisAlignment:
                                                  CrossAxisAlignment.start,
                                              children: [
                                                Text(
                                                  'Comment :  ${_commentStore.comments.length}',
                                                  style: TextStyle(
                                                    color: Colors.white,
                                                    fontSize: 16.sp,
                                                    fontWeight: FontWeight.bold,
                                                  ),
                                                ),
                                                SizedBox(height: 8.h),
                                                if (_commentStore.isLoading)
                                                  Center(
                                                    child:
                                                        CircularProgressIndicator(),
                                                  ),
                                                if (_commentStore
                                                        .errorMessage !=
                                                    null)
                                                  Text(
                                                    _commentStore.errorMessage!,
                                                    style: TextStyle(
                                                      color: Colors.red,
                                                    ),
                                                  ),
                                                if (!_commentStore.isLoading &&
                                                    _commentStore
                                                        .comments
                                                        .isEmpty)
                                                  Padding(
                                                    padding:
                                                        EdgeInsets.symmetric(
                                                          vertical: 32.h,
                                                        ),
                                                    child: Center(
                                                      child: Text(
                                                        'No comments yet. Be the first to comment!',
                                                        style: TextStyle(
                                                          color: Colors.white
                                                              .withAlpha(180),
                                                          fontSize: 15.sp,
                                                          fontFamily:
                                                              GoogleFonts.mochiyPopOne()
                                                                  .fontFamily,
                                                        ),
                                                      ),
                                                    ),
                                                  ),
                                                ..._commentStore.comments.map((
                                                  c,
                                                ) {
                                                  final commentUser =
                                                      _userService.getUserById(
                                                        c.userId,
                                                      );
                                                  return Container(
                                                    margin: EdgeInsets.only(
                                                      bottom: 10.h,
                                                    ),
                                                    padding: EdgeInsets.all(
                                                      10.w,
                                                    ),
                                                    decoration: BoxDecoration(
                                                      color: Colors.white
                                                          .withOpacity(0.08),
                                                      borderRadius:
                                                          BorderRadius.circular(
                                                            12.r,
                                                          ),
                                                      border: Border.all(
                                                        color: Colors.blueAccent
                                                            .withOpacity(0.2),
                                                      ),
                                                    ),
                                                    child: Column(
                                                      crossAxisAlignment:
                                                          CrossAxisAlignment
                                                              .start,
                                                      children: [
                                                        // 第一排：头像、用户名、举报按钮
                                                        Row(
                                                          children: [
                                                            GestureDetector(
                                                              onTap: () {
                                                                GoRouter.of(
                                                                  context,
                                                                ).push(
                                                                  AppRouter
                                                                      .otherProfile,
                                                                  extra: {
                                                                    'userId':
                                                                        commentUser
                                                                            ?.id,
                                                                  },
                                                                );
                                                              },
                                                              child: CircleAvatar(
                                                                radius: 16.r,
                                                                backgroundImage:
                                                                    AssetImage(
                                                                      commentUser
                                                                              ?.avatar ??
                                                                          'assets/images/touxiang1.png',
                                                                    ),
                                                              ),
                                                            ),
                                                            SizedBox(
                                                              width: 8.w,
                                                            ),
                                                            Text(
                                                              commentUser
                                                                      ?.name ??
                                                                  'Unknown',
                                                              style: TextStyle(
                                                                color:
                                                                    Colors
                                                                        .white,
                                                                fontWeight:
                                                                    FontWeight
                                                                        .bold,
                                                                fontSize: 14.sp,
                                                              ),
                                                            ),
                                                            Spacer(),
                                                            GestureDetector(
                                                              onTap: () async {
                                                                ReportDialog.show(
                                                                  context,
                                                                  title:
                                                                      'Report',
                                                                  description:
                                                                      'Please select a reason for reporting this comment.',
                                                                  onSubmit: (
                                                                    type,
                                                                  ) async {
                                                                    await getIt<
                                                                          ShareCommentService
                                                                        >()
                                                                        .deleteShareComment(
                                                                          c.id,
                                                                        );
                                                                    await _commentStore
                                                                        .loadComments(
                                                                          share!
                                                                              .id,
                                                                        );
                                                                  },
                                                                );
                                                              },
                                                              child: Icon(
                                                                MyIcons
                                                                    .iconReport,
                                                                color:
                                                                    Colors
                                                                        .white,
                                                                size: 22.sp,
                                                              ),
                                                            ),
                                                          ],
                                                        ),
                                                        SizedBox(height: 6.h),
                                                        // 第二排：评论内容
                                                        Text(
                                                          c.content,
                                                          style: TextStyle(
                                                            color: Colors.white,
                                                            fontSize: 13.sp,
                                                          ),
                                                        ),
                                                      ],
                                                    ),
                                                  );
                                                }).toList(),
                                                SizedBox(height: 20.h),
                                              ],
                                            ),
                                      ),
                                    ),
                                    SizedBox(height: 20.h),
                                  ],
                                ),
                              ),
                            ),
                          ],
                        ),
                      ),
                      // 悬浮底部评论输入框
                      Positioned(
                        left: 0,
                        right: 0,
                        bottom: 0,
                        child: Container(
                          padding: EdgeInsets.only(
                            left: 20.w,
                            right: 20.w,
                            bottom: 30.h,
                            top: 10.h,
                          ),
                          decoration: BoxDecoration(color: Colors.transparent),
                          child: Container(
                            height: 56.h,
                            decoration: BoxDecoration(
                              color: Color(0xFF121325),
                              borderRadius: BorderRadius.circular(12.r),
                              border: Border.all(color: Colors.white, width: 1),
                            ),
                            child: Row(
                              children: [
                                // 输入框
                                Expanded(
                                  child: Padding(
                                    padding: EdgeInsets.only(left: 20.w),
                                    child: TextField(
                                      controller: _commentController,
                                      style: TextStyle(color: Colors.white),
                                      decoration: InputDecoration(
                                        hintText: 'Leave A Comment',
                                        hintStyle: TextStyle(
                                          color: Colors.white.withAlpha(153),
                                          fontSize: 14.sp,
                                        ),
                                        border: InputBorder.none,
                                      ),
                                      keyboardType: TextInputType.text,
                                      textInputAction: TextInputAction.send,
                                      onSubmitted: (_) => _sendComment(),
                                    ),
                                  ),
                                ),
                                // 发送按钮
                                Padding(
                                  padding: EdgeInsets.only(right: 6.w),
                                  child: GestureDetector(
                                    onTap: _sendComment,
                                    child: Container(
                                      width: 75.w,
                                      height: 38.h,
                                      decoration: BoxDecoration(
                                        color: MyColors.blue,
                                        borderRadius: BorderRadius.circular(
                                          20.r,
                                        ),
                                      ),
                                      child: Center(
                                        child: Text(
                                          'Send',
                                          style: TextStyle(
                                            color: Colors.white,
                                            fontSize: 14.sp,
                                            fontWeight: FontWeight.bold,
                                          ),
                                        ),
                                      ),
                                    ),
                                  ),
                                ),
                              ],
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
        ),
      ),
    );
  }
}
